/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { ModuleType } from '../../enum/module-type-enum.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { AbstractHapModulePlugin } from '../common/abstract-hap-module-plugin.js';
import { AbstractHarModulePlugin } from '../common/abstract-har-module-plugin.js';

export class PluginInspector {
  private static _log = OhosLogger.getLogger('hvigor-plugin-factory');

  /**
   * 校验feature模块的entryModules中的字段是否合法的entry
   * @param hapPlugin
   * @public
   */
  public static checkFeatureEntryModules(hapPlugin: AbstractHapModulePlugin) {
    const moduleModel = hapPlugin.getModuleModel()!;
    const moduleType = moduleModel.getModuleType();
    if (moduleType !== ModuleType.Feature) {
      return;
    }

    // 这一部分校验不能直接执行,需要在hvigor将所有node模块都evaluated后才校验,
    // 因为getAllEntryModules()中在该阶段之后才能获取所有模块的模块信息
    const entryModules = moduleModel.getProfileOpt().entryModules;
    if (entryModules === undefined) {
      return;
    }
    const entries: Set<string> = hapPlugin.getProjectModel()!.getAllEntryModules();
    if (
      !entryModules!.every((configEntry) => {
        return entries.has(configEntry);
      })
    ) {
      // 存在配置不正确的entry
      this._log.printErrorExit(
        'ERROR_ENTRY_CONFIG',
        [],
        [[moduleModel.getName(), moduleModel.getProfilePath()]]
      );
    }
  }

  /**
   * 检查原子化服务是否依赖hsp
   * @param hapPlugin
   * @public
   */
  public static checkAtomicServiceHspModules(hapPlugin: AbstractHarModulePlugin) {
    const moduleModel = hapPlugin.getModuleModel();
    const hasHspDependency = hapPlugin.getTaskService()?.hasHspDependencies();
    if (moduleModel?.isInstallFree() && hasHspDependency) {
      this._log.printErrorExit(
        'ATOMIC_SERVICE_RELY_HSP',
        [moduleModel?.getName()]
      );
    }
  }
}
